package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.QuestionItem;
import com.wuwei.elearning.question.domain.QuestionItemRaletionQuestion;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.domain.TestResult;
import com.wuwei.elearning.question.mapper.QuestionItemMapper;
import com.wuwei.elearning.question.mapper.QuestionItemRaletionQuestionMapper;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.mapper.TestResultMapper;
import com.wuwei.elearning.question.vo.EChartsPieVo;
import com.wuwei.elearning.question.vo.GetResultVo;
import com.wuwei.elearning.question.vo.PageVo;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import com.wuwei.elearning.vo.TestResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 考试结果存储的表 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-01-18
 */
@RestController
@RequestMapping("/elearning/testResult")
@CrossOrigin
public class TestResultController {

    @Resource
    private TestResultMapper testResultMapper;


    @Autowired
    private HttpServletRequest request;

    /**
     * 分页获取test_result列表的方法
     * @param resultVoPageVo
     * @return
     */
    @PostMapping("getList")
    public Result< List<TestResultVo>> getList(@RequestBody PageVo<GetResultVo> resultVoPageVo ){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        int currentPage = resultVoPageVo.getCurrentPage();
        int pageSize = resultVoPageVo.getPageSize();
        int skipPage = (currentPage - 1) * pageSize;
        String role = resultVoPageVo.getParams().getRole();
        String title = resultVoPageVo.getParams().getTitle();
        LocalDateTime startTime = null;
        if (resultVoPageVo.getParams().getStartTime() != null) {
            startTime = LocalDateTime.of(resultVoPageVo.getParams().getStartTime().toLocalDate(), LocalTime.MIN);
        }
        LocalDateTime endTime = null;
        if (resultVoPageVo.getParams().getEndTime() != null) {
            endTime = LocalDateTime.of(resultVoPageVo.getParams().getEndTime().toLocalDate(), LocalTime.MAX); // 按需调整精度
        }
        List<TestResultVo> testResultVos = new ArrayList<>();
        //这里角色有 TA PA 补差 其他 以后还会有很多，但是只有管理员和老师才有权限查看所有
        if (!"admin".equals(role)&&!"teacher".equals(role)) {
            testResultVos = testResultMapper.myConditionQueryByStudent(account,title,startTime,endTime,pageSize,skipPage);
        }else{
            testResultVos = testResultMapper.myConditionQuery(title,startTime,endTime,pageSize,skipPage);
        }

        for (TestResultVo testResult : testResultVos) {
            Long questionItemId = testResult.getQuestionItemId();
            QuestionItem questionItem = questionItemMapper.selectById(questionItemId);
            if (questionItem!=null) {
                Long subjectId = questionItem.getSubjectId();
                Subject subject = subjectMapper.selectById(subjectId);
                if (subject!=null) {
                    testResult.setSubjectName(subject.getName());
                }
            }
            LambdaQueryWrapper<QuestionItemRaletionQuestion> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(QuestionItemRaletionQuestion::getQuestionItemId, questionItemId);
            Long count = questionItemRaletionQuestionMapper.selectCount(queryWrapper1);
            testResult.setTestCount(count);
        }
        return Result.ok(testResultVos);
    }

    @Resource
    private QuestionItemMapper questionItemMapper;

    @Resource
    private SubjectMapper subjectMapper;

    @Resource
    private QuestionItemRaletionQuestionMapper questionItemRaletionQuestionMapper;

    /**
     * 获取所有考试成绩的方法
     * 该方法学员和教员都可以调用
     * 会在参数中判断role属性，如果role属性是teacher，则可以查看所有考试成绩
     * 如果role属性是student，则只能查看自己的考试成绩
     * @return
     */
    @PostMapping("getTotal")
    public Result<Long> getTotal (@RequestBody GetResultVo resultVoPageVo){

        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        String role = resultVoPageVo.getRole();
        String title = resultVoPageVo.getTitle();
        LocalDateTime startTime = null;
        if (resultVoPageVo.getStartTime() != null) {
            startTime = LocalDateTime.of(resultVoPageVo.getStartTime().toLocalDate(), LocalTime.MIN);
        }
        LocalDateTime endTime = null;
        if (resultVoPageVo.getEndTime() != null) {
            endTime = LocalDateTime.of(resultVoPageVo.getEndTime().toLocalDate(), LocalTime.MAX); // 按需调整精度
        }
        Long count;
        if (!"admin".equals(role)&&!"teacher".equals(role)) {
            count = testResultMapper.myConditionCountByStudent(account,title,startTime,endTime);
        }else{
            count = testResultMapper.myConditionCount(title,startTime,endTime);
        }
        return Result.ok(count);
    }

    /**
     * 获取该用户所有刷过的题目
     * @return
     */
    @GetMapping("analysis/all")
    public Result<Map<String,Object>> analysisAll(){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);

        LambdaQueryWrapper<TestResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestResult::getAccount,account);
        List<TestResult> testResults = testResultMapper.selectList(queryWrapper);
        Map<String,Object> map = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        List<LocalDate> xaxis = new ArrayList<>();
        List<Integer> yaxis = new ArrayList<>();
        testResults.forEach(testResult -> {
            Integer score = testResult.getScore();
            LocalDateTime createTime = testResult.getCreateTime();
            LocalDate localDate = createTime.toLocalDate();
            xaxis.add(localDate);
            yaxis.add(score);
            ids.add(testResult.getId());
        });
        map.put("xaxis",xaxis);
        map.put("yaxis",yaxis);
        map.put("ids",ids);
        return Result.ok(map);
    }

    /**
     * 获取该用户所有刷过的题目
     * @return
     */
    @GetMapping("analysis/{subjectId}")
    public Result<Map<String,Object>> analysisAll(@PathVariable("subjectId") Long subjectId){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);

        List<TestResult> testResults = testResultMapper.selectBySubjectId(account,subjectId);
        Map<String,Object> map = new HashMap<>();
        List<Long> ids = new ArrayList<>();
        List<LocalDate> xaxis = new ArrayList<>();
        List<Integer> yaxis = new ArrayList<>();
        testResults.forEach(testResult -> {
            Integer score = testResult.getScore();
            LocalDateTime createTime = testResult.getCreateTime();
            LocalDate localDate = createTime.toLocalDate();
            xaxis.add(localDate);
            yaxis.add(score);
            ids.add(testResult.getId());
        });
        map.put("xaxis",xaxis);
        map.put("yaxis",yaxis);
        map.put("ids",ids);
        return Result.ok(map);
    }



    /**
     * 按照课程分类获取各课程刷过题目的数量
     */
    @GetMapping("analysis/numbers")
    public Result<List<EChartsPieVo>> analysisNumbers(){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<EChartsPieVo> maps = questionItemMapper.selectQuestionIdByAccount(account);
        return Result.ok(maps);
    }

    @GetMapping("getById/{id}")
    public Result<TestResult> getById(@PathVariable("id")Long id){
        TestResult testResult = testResultMapper.selectById(id);
        return Result.ok(testResult);
    }
}

